package com.zzyl.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.BCUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.UserService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.UserVo;
import javassist.expr.NewArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;


    //分页
    @Override
    public PageResponse<UserVo> findUserVoPage(UserDto userDto, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);

       Page<UserVo> userVoPage = (Page<UserVo>) userMapper.findUserVoPage(userDto);
       return PageResponse.of(userVoPage, UserVo.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addUser(UserDto userDto) {
        //1.保存用户表
        User user = BeanUtil.toBean(userDto, User.class);
        String password = BCrypt.hashpw("888itcast.CN764%…");
        user.setPassword(password);
        userMapper.insert(user);

        //2.保存用户角色表

        //获取角色的所有id
        Set<String> roleVoIds = userDto.getRoleVoIds();


        //创建一个空的集合
        List<UserRole> list = new ArrayList<>();
        //遍历id
//        Long userId, Long roleId, String dataState
        for (String roleVoId : roleVoIds) {
            UserRole userRole = new UserRole(user.getId(),Long.parseLong(roleVoId),"0");
            userRoleMapper.insert(userRole);
            list.add(userRole);
        }

        userRoleMapper.batchInsert(list);

        return true;
    }

    @Override
    public UserVo login(LoginDto loginDto) {
       //根据用户名查询用户
        User user = userMapper.findByUsername(loginDto.getUsername());
        // ObjectUtil.isEmpty 用于检查user对象是否为空
        if(ObjectUtil.isEmpty(user)){
            //登录失败
            throw new BaseException(BasicEnum.LOGIN_FAIL);

        }
        //2.判断是否被禁用
        if(user.getDataState().equals(SuperConstant.DATA_STATE_1)) {
            throw new BaseException(BasicEnum.ACCOUNT_DISABLED);
        }
        //3.判断密码是否正确
        if(!BCrypt.checkpw(loginDto.getPassword(),user.getPassword())){
            //登录失败
            throw new BaseException(BasicEnum.INCORRECT_PASSWORD);
        }
        //4.密码脱敏
        user.setPassword("");

        UserVo userVo = BeanUtil.toBean(user, UserVo.class);
        //5.使用JWT生成token
        HashMap<String, Object> claims = new HashMap<>();

        claims.put("currentUser", JSONUtil.toJsonStr(userVo) );
        String jwt = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), jwtTokenManagerProperties.getTtl(), claims);
        userVo.setUserToken(jwt);
        return userVo;
    }
}
